#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

const static uint16_t gport = 8888;
const static int glistensockfd = -1;
const static int gblcklog = 8;

using service_io_t = std::function<void(SockPtr, InetAddr &)>;


class TcpServer
{
    class ThreadData
    {
    public:
        SockPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;

        ThreadData(SockPtr sockfd, TcpServer *self, InetAddr addr) : _sockfd(sockfd), _self(self), _addr(addr) {}
    };

public:
    TcpServer(service_io_t service, uint16_t port = gport) : _service(service), _port(port), _listensockfd(std::make_shared<TcpSocket>()), _isrunning(false)
    {
        _listensockfd->BuildListenSocket(_port);
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            SockPtr newsock=_listensockfd->Accepter(&client);
            if(newsock==nullptr)
                continue;
        
            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n", client.AddrStc().c_str(), newsock->Sockfd());
            //version3 多线程版
             pthread_t tid;
             ThreadData *td=new ThreadData(newsock,this,client);
             pthread_create(&tid,nullptr,Excute,td);
        }
        _isrunning = false;
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

private:
    uint16_t _port;
    SockPtr _listensockfd;
    bool _isrunning;
    service_io_t _service;
};